#include <iostream>
#include <cassert>
#include <unistd.h>
#include <cstring>
#include <sys/stat.h>
#include <sys/wait.h>

using namespace std;
int main()
{
    int fds[2];

    int i = pipe(fds);
    assert(i == 0);

    int id = fork();
    assert(id != -1);

    if (id == 0)
    {
        // 子进程
        close(fds[0]);
        const char *s = "我是子进程，我在给你发消息";
        int cnt = 0;
        while (true)
        {
            char buffer[1024];
            snprintf(buffer, sizeof buffer, "%s:[%d],我的pid是：%d", s, cnt++, getpid());
            // 写端写满时会阻塞
            write(fds[1], buffer, strlen(buffer));
            cout << "count:" << cnt << endl;
            // sleep(5);
            // break;
        }

        close(fds[1]);
        cout << "子进程关闭自己的写端" << endl;
        exit(0);
    }

    // 父进程
    close(fds[1]);
    while (true)
    {
        sleep(2);
        char buffer[1024];
        // 管道没数据时，读端会阻塞
        ssize_t s = read(fds[0], buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "#" << buffer << " |  my pid:" << getpid() << endl;
        }
        else if(s == 0)break;   //写端关闭，读端也关闭
        //读端先关闭
        break;
    }

    close(fds[0]);
    cout << "父进程关闭读端" << endl;

    int status = 0;
    int n = waitpid(id, &status, 0);
    assert(n == id);

    cout << "pid->" << n << " sigcode: " << (status & 0x7F) << endl;


    return 0;
}
